package com.itlong.cloud.operate.service.impl;

import com.itlong.cloud.POJO.DTO.operate.OperateAdInfoGetPageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateSaveAdImgDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateSaveAdInfoDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateUpdateAdInfoDTO;
import com.itlong.cloud.POJO.PO.AdImagePO;
import com.itlong.cloud.POJO.PO.AdPO;
import com.itlong.cloud.POJO.PO.AdServeProjectPO;
import com.itlong.cloud.POJO.VO.operate.OperateAdGetOneVO;
import com.itlong.cloud.POJO.VO.operate.OperateAdImgVO;
import com.itlong.cloud.POJO.VO.operate.OperateAdVO;
import com.itlong.cloud.POJO.VO.operate.OperateProjectInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.DeviceMediaInfoPublishStatusEnum;
import com.itlong.cloud.enumerate.SystemTypeEnum;
import com.itlong.cloud.operate.dao.IOperateAdDao;
import com.itlong.cloud.operate.dao.IOperateAdImgDao;
import com.itlong.cloud.operate.dao.IOperateAdServeProjectDao;
import com.itlong.cloud.operate.service.IOperateAdManageService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * <desc>
 *      运营-运营管理-广告管理服务接口实现类。
 * <desc/>
 *
 * @createDate 2017/10/10.
 */
@Service
public class OperateAdManageServiceImpl implements IOperateAdManageService {

    private static final Logger LOG = LoggerFactory.getLogger(OperateAdManageServiceImpl.class);

    //广告信息
    @Autowired
    IOperateAdDao iOperateAdDao;

    //广告图片信息
    @Autowired
    IOperateAdImgDao iOperateAdImgDao;

    //广告项目
    @Autowired
    IOperateAdServeProjectDao iOperateAdServeProjectDao;


     /**
      * <desc>
      *      从数据传输对像获取广告实体对象。
      * <desc/>
      *
      * @param  saveDTO 添加广告请求参数对象
      * @return
      * @author shengen.T
      * @createDate 2017/10/11
      */
     private AdPO getAdPOInfo(OperateSaveAdInfoDTO saveDTO) throws Exception{
         AdPO adPO = new AdPO();
         BeanUtils.copyProperties(saveDTO,adPO);
         adPO.setAdId(LogicIdUtil.bussinessId());
         if (saveDTO.getSystemType().equals(SystemTypeEnum.OPERATE.getType())){
             adPO.setPublishState(DeviceMediaInfoPublishStatusEnum.UNPUBLISHED.getType());
         }else {
             adPO.setPublishState(DeviceMediaInfoPublishStatusEnum.UN_CHECKED.getType());
         }
         Date nowTime = new Date();
         adPO.setCreateTime(nowTime);
         adPO.setUpdateTime(nowTime);
         adPO.setStartTime(saveDTO.getPublishStartDate());
         adPO.setEndTime(saveDTO.getPublishEndDate());
         return adPO;
     }


     /**
      * <desc>
      *      保存广告信息。
      * <desc/>
      *
      * @param saveDTO 广告请求保存的数据对象
      * @return
      * @author shengen.T
      * @createDate 2017/10/11
      */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveAdInfo(OperateSaveAdInfoDTO saveDTO) throws Exception {
         Integer flag=1;
        //保存广告信息
         AdPO adPO = null;
         adPO = this.getAdPOInfo(saveDTO);
         Integer adCount = 0;
         adCount = iOperateAdDao.save(SqlUtil.durableData(adPO, PlatformConstants.TABLE_SAVE));

         //保存图片链接信息
         Integer adImgCount = 0;
         List<OperateSaveAdImgDTO> saveAdImgDtoArr = saveDTO.getImgInfoVO();
         for (OperateSaveAdImgDTO adImgDto:saveAdImgDtoArr){
             if(StringUtils.isNotEmpty(adImgDto.getImgUrl()))
             {
                 AdImagePO adImagePO = new AdImagePO(adPO.getAdId(),
                         adImgDto.getImgUrl(),
                         adImgDto.getJumpUrl(),
                         adImgDto.getRemark());
                 adImgCount += iOperateAdImgDao.save(SqlUtil.durableData(adImagePO, PlatformConstants.TABLE_SAVE));
             }

         }

         //保存广告项目对应信息
         AdServeProjectPO adServeProjectPO = new AdServeProjectPO();
         List<Map<String,Object>> adP0rojectList= new ArrayList<>();
        String pushInfoId[] = StringHandlerUtil.splitString(saveDTO.getProjectIds());
         Integer adProjestCount=0;
         for (int i=0;i< pushInfoId.length;i++){
             adServeProjectPO.setAdId(adPO.getAdId());
             adServeProjectPO.setProjectId(pushInfoId[i]);
             iOperateAdServeProjectDao.save(SqlUtil.durableData(adServeProjectPO, PlatformConstants.TABLE_SAVE));
         }
        if((adCount<1)||(adImgCount<1)||(adProjestCount<1)){
           flag=0;
        }
         return flag;
    }

     /**
      * <desc>
      *      修改广告信息。
      * <desc/>
      *
      * @param  updateDTO
      * @return
      * @author shengen.T
      * @createDate 2017/10/17
      */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer updateAdInfo(OperateUpdateAdInfoDTO updateDTO) throws Exception{

        Integer flag=0;
        //修改广告信息
        Integer adCount = 0;
        AdPO adPO = new AdPO(updateDTO.getAdId(),
                updateDTO.getTitle(),
                updateDTO.getType(),
                updateDTO.getStatus()
                );
        adPO.setUpdateTime(new Date());
        adPO.setStartTime(updateDTO.getPublishStartDate());
        adPO.setEndTime(updateDTO.getPublishEndDate());
        adPO.setPublishPlatform(updateDTO.getPublishPlatform());
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        Date startTime = sdf.parse(updateDTO.getPublishStartDate());
        Date endTime = sdf.parse(updateDTO.getPublishEndDate());
        if (SystemTypeEnum.OPERATE.getType().equals(updateDTO.getSystemType())){
            adPO.setPublishState(this.calculateDeviceMediaPublishStatus(startTime, endTime, new Date()));
        }else {
            adPO.setPublishState(DeviceMediaInfoPublishStatusEnum.UN_CHECKED.getType());
        }
        adCount =iOperateAdDao.update(SqlUtil.durableData(adPO, PlatformConstants.TABLE_UPDATE));

        //修改广告图片信息
        Integer adImgCount = 0;
        iOperateAdImgDao.delete(updateDTO.getAdId());
        List<OperateSaveAdImgDTO> saveAdImgDtoArr = updateDTO.getImgInfoVO();
        for (OperateSaveAdImgDTO adImgDto:saveAdImgDtoArr){
             if(StringUtils.isNotEmpty(adImgDto.getImgUrl())){
                 AdImagePO adImagePO = new AdImagePO(updateDTO.getAdId(),
                         adImgDto.getImgUrl(),
                         adImgDto.getJumpUrl(),
                         adImgDto.getRemark());
                 adImgCount += iOperateAdImgDao.save(SqlUtil.durableData(adImagePO, PlatformConstants.TABLE_SAVE));

             }
             }

        //修改广告项目对应信息
        AdServeProjectPO adServeProjectPO = new AdServeProjectPO();
        Integer adProjestCount=0;
        String pushInfoId[] = StringHandlerUtil.splitString(updateDTO.getProjectIds());
        iOperateAdServeProjectDao.delete(updateDTO.getAdId());
        for (int i=0;i< pushInfoId.length;i++){
            adServeProjectPO.setAdId(updateDTO.getAdId());
            adServeProjectPO.setProjectId(pushInfoId[i]);
            iOperateAdServeProjectDao.save(SqlUtil.durableData(adServeProjectPO, PlatformConstants.TABLE_SAVE));
        }
        if((adCount>0)||(adImgCount>0)||(adProjestCount>0)){
            flag=0;
        }
        return flag;
    }

    /**
     * <desc>
     *      根据广告投放开始和结束时间推算多媒体资源的发布状态
     * </desc>
     *
     * @param putStartTime 多媒体资源投放开始时间
     * @param putEndTime 多媒体资源投放结束时间
     * @param date 用来比较的基准时间
     * @return 多媒体资源发布状态
     * @author wangzhi
     * @createDate 2018-04-09
     */
    public Integer calculateDeviceMediaPublishStatus(Date putStartTime,Date putEndTime,Date date){
        // publishStatus 发布状态0-已过期 1-已发布 2-未发布
        if (putStartTime.compareTo(date) > 0){
            // 投放开始时间大于date，未发布
            return 2;
        }
        if (putStartTime.compareTo(date) < 0 && putEndTime.compareTo(date) >0){
            // date在投放时间区间中，已发布
            return 1;
        }
        if (putEndTime.compareTo(date) < 0){
            // 投放结束时间小于date，已过期
            return 0;
        }
        return null;
    }

     /**
      * <desc>
      *      批量发布广告。
      * <desc/>
      *
      * @param  adIds
      * @return
      * @author shengen.T
      * @createDate 2017/10/17
      */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer publishAd(String adIds) throws Exception{
        //广告ID列表
        String adId[]=  StringHandlerUtil.splitString(adIds);
        return  iOperateAdDao.publishAd(adId,new Date());
    }

    /**
     * <desc>
     *      批量删除广告。
     * <desc/>
     *
     * @param  adIds
     * @return
     * @author shengen.T
     * @createDate 2017/10/17
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer deleteAd(String adIds) throws Exception{
        //广告ID列表
        String adId[]=  StringHandlerUtil.splitString(adIds);
        //逻辑删除广告状态
        iOperateAdDao.deleteAd(adId,new Date());
        //删除广告图片关系表
        iOperateAdImgDao.deleteBatch(adId);
        //删除广告项目关系表
         iOperateAdServeProjectDao.deleteBatch(adId);
        return 1;
    }

     /**
      * <desc>
      *      设置广告状态。
      * <desc/>
      *
      * @param  adId 广告ID
      * @param  status 状态
      * @return
      * @author shengen.T
      * @createDate 2017/10/17
      */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer setAdStatus(String adId,Integer status) throws Exception {
      return iOperateAdDao.setStatus(adId,status);
    }

     /**
      * <desc>
      *      获取广告信息。
      * <desc/>
      *
      * @param  adId 广告ID
      * @return
      * @author shengen.T
      * @createDate 2017/10/17
      */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public OperateAdGetOneVO getAdInfo(String adId) throws Exception{
        OperateAdGetOneVO adVO = iOperateAdDao.getOne(adId);
        if(adVO!=null){
            List<OperateProjectInfoVO> projectInfoVOS = iOperateAdDao.getProjectList(adId);
            List<OperateAdImgVO> adImgVOS = iOperateAdImgDao.getImgInfoList(adId);
            adVO.setImgInfoVO(adImgVOS);
            adVO.setProjectInfos(projectInfoVOS);
        }
        return adVO;
    }

     /**
      * <desc>
      *      分页查询广告信息列表。
      * <desc/>
      *
      * @param  pageDTO 条件查询请求参数
      * @return
      * @author shengen.T
      * @createDate 2017/10/17
      */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<OperateAdVO> getAdInfoPage(OperateAdInfoGetPageDTO pageDTO) throws Exception{
        //分页对象
        Page<OperateAdVO> page = new Page<>();
        //将DTO转换为Map
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(pageDTO, page);
        //查询
        List<OperateAdVO> AdInfoVOS = iOperateAdDao.getPage(params);
        if((AdInfoVOS != null)&&(AdInfoVOS.size()>0)){
            List<OperateAdImgVO> adImgVOS = null;
            for(OperateAdVO adVO:AdInfoVOS){
                adImgVOS = iOperateAdImgDao.getImgInfoList(adVO.getAdId());
                adVO.setImgInfoVO(adImgVOS);
            }
        }
        Integer count = iOperateAdDao.getPageCount(params);
        //填充返回数据集
        page.setRows(AdInfoVOS, count);
        return page;
    }

    /**
     * <desc>
     * 获取最新广告Banner图片列表
     * <desc/>
     *
     * @param projectId 项目id
     * @param type      广告类型（1主页，2服务页，3物业服务页）
     * @param publishPlatform 发布平台（1APP，2小程序）
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-08
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<OperateAdImgVO> getBannerImgs(String projectId, Integer type,Integer publishPlatform) throws Exception {
        //返回最新3条广告里的所有图片
        return iOperateAdImgDao.getProjectAdImgs(projectId, type, new Date(),3,publishPlatform);
    }

    /**
     * <desc>
     *      检测过期广告并将发布状态置为过期。
     * <desc/>
     *
     * @param
     * @return
     * @author shengen.T
     * @createDate 2017/11/24
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean changePublishStateTimeTask() throws Exception{
        Date nowTime = new Date();
        List<String> IdList = iOperateAdDao.getDisabledAdIdList(nowTime);
        List<String> willPublishIdList = iOperateAdDao.getWillPublishIdList(nowTime);
        if (!willPublishIdList.isEmpty()){
            iOperateAdDao.batchUpdatePublishStatus(willPublishIdList);
        }
        boolean isSuccess=false;
        if((IdList!=null)&&(IdList.size()>0)){
            iOperateAdDao.setPublishStateBatch(IdList);
            isSuccess = true;
        }
        return isSuccess;
    }

    /**
     * <desc>
     * 广告审核
     * </desc>
     *
     * @param operateAdInfoGetPageDTO 参数DTO
     * @return
     * @Author Zhu.yj
     * @createDate 2020/12/24
     */
    @Override
    public Integer audit(OperateAdInfoGetPageDTO operateAdInfoGetPageDTO) throws Exception {
        Map<String, Object> params = new HashMap<>();
        Date nowTime = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        OperateAdGetOneVO adVO = iOperateAdDao.getOne(operateAdInfoGetPageDTO.getAdId());
        if(adVO != null){
            if (DataStatusEnum.DELETE.getType().toString().equals(operateAdInfoGetPageDTO.getAuditStatus())){
                params.put("publishStatus", DeviceMediaInfoPublishStatusEnum.UN_PASSES.getType());
            }else {
                //发布日期之前，状态置为未发布
                if (nowTime.before(dateFormat.parse(adVO.getPublishStartDate()))){
                    params.put("publishStatus", DeviceMediaInfoPublishStatusEnum.UNPUBLISHED.getType());
                }
                //发布日期之中，状态置为已发布
                if (nowTime.after(dateFormat.parse(adVO.getPublishStartDate())) && nowTime.before(dateFormat.parse(adVO.getPublishEndDate()))){
                    params.put("publishStatus", DeviceMediaInfoPublishStatusEnum.PUBLISHED.getType());
                }
                //发布日期之后，状态置为已过期
                if (nowTime.after(dateFormat.parse(adVO.getPublishEndDate()))){
                    params.put("publishStatus", DeviceMediaInfoPublishStatusEnum.OUT_OF_DATE.getType());
                }
            }
            params.put("auditRemark", operateAdInfoGetPageDTO.getAuditRemark());
            params.put("updateTime", nowTime);
            params.put("adId", operateAdInfoGetPageDTO.getAdId());
            iOperateAdDao.audit(params);
        }

        return null;
    }

}
